from django.shortcuts import render,redirect
from . import models
from user.models import User

# Create your views here.
def Plate_list(request):
    if(request.session.get('is_login')):
        if(User.objects.get(username = request.session.get('username')).is_forbidden):
            request.session['is_forbidden'] = True
        else:
            request.session['is_forbidden'] = False
    context = {}
    context['plates'] = models.Plate.objects.all()
    context['posts'] = models.Post.objects.all()[:30]
    return render(request,'post/plate_list.html',context)

def Plate_detail(request,key):
    if(request.session.get('is_login')):
        if(User.objects.get(username = request.session.get('username')).is_forbidden):
            request.session['is_forbidden'] = True
        else:
            request.session['is_forbidden'] = False
    if request.method == "POST":
        post = models.Post.objects.create()
        post.title = request.POST.get('title').strip()
        post.content = request.POST.get('text').strip()
        if post.title and post.content:
            post.plate = models.Plate.objects.get(key=key).name
            post.key = models.Post.objects.all().count()
            user = User.objects.get(username=request.session.get('username'))
            post.user = user
            user.point = user.point + 5
            request.session['point'] = user.point
            user.save()
            post.save()
            plate = models.Plate.objects.get(key=key)
            return redirect('plate_detail',key)
        else:
            return redirect('plate_detail',key)
    plate = models.Plate.objects.get(key=key)
    context = {}
    context['name'] = plate.name
    context['posts'] = models.Post.objects.filter(plate=plate.name)
    context['key'] = plate.key
    return render(request,'post/plate_detail.html',context)

def Post_detail(request,key):
    if(request.session.get('is_login')):
        if(User.objects.get(username = request.session.get('username')).is_forbidden):
            request.session['is_forbidden'] = True
        else:
            request.session['is_forbidden'] = False
    if request.method == 'POST':
        comment = models.Comment.objects.create()
        comment.key = key
        comment.content = request.POST.get('text')
        user = User.objects.get(username = request.session.get('username'))
        comment.user = user
        user.point = user.point + 3
        request.session['point'] = user.point
        user.save()
        comment.save()
        return redirect('post_detail',key)
    context = {}
    context['post'] = models.Post.objects.get(key=key)
    context['comments'] = models.Comment.objects.filter(key=key)
    return render(request,'post/post_detail.html',context)